package com.sf.service;

import com.google.common.collect.ArrayListMultimap;
import com.google.common.collect.Lists;
import com.google.common.collect.Multimap;
import com.sf.dao.RfDeptMapper;
import com.sf.dto.DeptLevelDto;
import com.sf.model.RfDept;
import com.sf.util.LevelUtil;
import org.apache.commons.collections.CollectionUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Comparator;
import java.util.List;

@Service
public class RfTreeService {

    @Resource
    private RfDeptMapper rfDeptMapper;

    public List<DeptLevelDto> deptTree() {
        List<RfDept> deptList = rfDeptMapper.getAllDept();
        List<DeptLevelDto> dtoList = Lists.newArrayList();
        for (RfDept dept : deptList) {
            DeptLevelDto dto = DeptLevelDto.adapt(dept);
            dtoList.add(dto);
        }
        return deptList2Tree(dtoList);
    }

    private List<DeptLevelDto> deptList2Tree(List<DeptLevelDto> deptLevelDtoList) {

        if (CollectionUtils.isEmpty(deptLevelDtoList)) {
            return Lists.newArrayList();
        }
        Multimap<String, DeptLevelDto> levelDtoMultiMap = ArrayListMultimap.create();
        List<DeptLevelDto> rootList = Lists.newArrayList();
        for (DeptLevelDto dto : deptLevelDtoList) {
            levelDtoMultiMap.put(dto.getLevel(), dto);
            if (LevelUtil.ROOT.equals(dto.getLevel())) {
                rootList.add(dto);
            }
        }
        //seq从小到大排序
        rootList.sort(Comparator.comparingInt(DeptLevelDto::getSeq));
        transformDeptTree(rootList, LevelUtil.ROOT, levelDtoMultiMap);
        return rootList;
    }


    //递归生成树
    private void transformDeptTree(List<DeptLevelDto> deptLevelDtoList, String level,
                                   Multimap<String, DeptLevelDto> levelDtoMultiMap) {

        for (DeptLevelDto deptLevelDto : deptLevelDtoList) {
            //遍历该层级元素
            //处理当前层级数据
            String nextLevel = LevelUtil.calculateLevel(level, deptLevelDto.getId());
            //处理下层
            List<DeptLevelDto> deptLevelDtoList1 = (List<DeptLevelDto>) levelDtoMultiMap.get(nextLevel);
            if (CollectionUtils.isNotEmpty(deptLevelDtoList1)) {
                //排序
                deptLevelDtoList1.sort(Comparator.comparingInt(DeptLevelDto::getSeq));
                //设置下层部门
                deptLevelDto.setDeptList(deptLevelDtoList1);
                //进入下层处理
                transformDeptTree(deptLevelDtoList1, nextLevel, levelDtoMultiMap);
            }
        }
    }


}
